package org.fessingapore.library.daos.impl;

import java.sql.SQLException;
import java.util.List;

import org.fessingapore.library.daos.MemberDao;
import org.fessingapore.library.models.Group;
import org.fessingapore.library.models.Loan;
import org.fessingapore.library.models.Member;
import org.fessingapore.library.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class MemberDaoImpl extends GenericDaoImpl<Member, Integer> implements MemberDao{

	private Session session;
	
	public List<Member> search(Member member) throws SQLException {
		session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(Member.class, "member");
        
        if (member.getNric() != null && !member.getNric().equals("")){
        	criteria.add(Restrictions.like("member.nric", "%"+member.getNric()+"%"));
        }
        
        
        if (member.getEmail() != null && !member.getEmail().equals("")){
        	criteria.add(Restrictions.like("member.email", "%"+member.getEmail()+"%"));
        }
        
        if (member.getEmail() != null && !member.getEmail().equals("")){
        	criteria.add(Restrictions.like("member.email", "%"+member.getEmail()+"%"));
        }
        
        if (member.getUsername()!=null && !member.getUsername().equals("")){
            criteria.add(Restrictions.like("member.username", "%"+member.getUsername()+"%"));
        }
        
        if (member.getFirstname()!=null && !member.getFirstname().equals("")){
            criteria.add(Restrictions.or(Restrictions.like("member.firstname", "%"+member.getFirstname()+"%"),Restrictions.like("member.lastname", "%"+member.getFirstname()+"%")));
        }
        
        if (member.getGroups() != null && !member.getGroups().isEmpty()){
        	criteria.createAlias("member.groups", "group")
        	.add(Restrictions.eq("group.id", member.getGroups().get(0).getId()));
        }
        
        List<Member> memberList = criteria.list();
        clear();
        return memberList;
	}

	
}
